<template>
  <el-dialog :visible.sync="dialogVisible" width="80%">
    <baidu-map
      class="map"
      :center="center"
      :zoom="zoom"
      @click="onMapClick"
    >
      <bm-local-search
        ref="localSearch"
        :keyword="keyword"
        @searchcomplete="onSearchComplete"
      ></bm-local-search>
      <bm-marker
        v-if="selectedPoint"
        :position="{ lng: selectedPoint.lng, lat: selectedPoint.lat }"
      >
      </bm-marker>
    </baidu-map>
    <div style="padding: 15px;">
      <el-input v-model="keyword" placeholder="请输入搜索关键词" @keyup.enter="search">
        <template slot="append">
          <el-button icon="el-icon-search" @click="search">搜索</el-button>
        </template>
      </el-input>
      <ul class="search-results">
        <li v-for="(result, index) in searchResults" :key="index" @click="selectPoint(result)">
          {{ result.title }}
        </li>
      </ul>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'MapDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      center: { lng: 116.404, lat: 39.915 }, // 中心点默认北京
      zoom: 15,
      keyword: '',
      searchResults: [],
      selectedPoint: null
    };
  },
  watch: {
    visible(val) {
      this.dialogVisible = val;
    },
    dialogVisible(val) {
      this.$emit('update:visible', val);
    }
  },
  methods: {
    search() {
      // 触发POI搜索
      this.$refs.localSearch.search(this.keyword);
    },
    onMapClick(e) {
      // 创建逆地理编码实例
      const geocoder = new BMap.Geocoder();
      const pt = new BMap.Point(e.point.lng, e.point.lat);

      // 将点击的坐标点转换成地址信息
      geocoder.getLocation(pt, (rs) => {
        const address = rs.addressComponents;
        const fullAddress = `${address.province}${address.city}${address.district}${address.street}${address.streetNumber}`;

        // 设置选中点，并包含地址信息
        this.selectedPoint = {
          lng: e.point.lng,
          lat: e.point.lat,
          address: fullAddress // 地址信息
        };

        this.searchResults = [];
        // 发出事件
        this.$emit('point-selected', this.selectedPoint);
      });
    },
    onSearchComplete(data) {
      // 搜索完成事件
      if (data.content) {
        this.searchResults = data.content;
      }
    },
    selectPoint(point) {
      // 选点事件
      this.selectedPoint = { lng: point.location.lng, lat: point.location.lat,address: point.address};
      this.searchResults = [];
      this.$emit('point-selected', this.selectedPoint);
      this.$emit('update:visible', false); // Optionally close dialog on selection
    }
  }
};
</script>

<style scoped>
.map {
  width: 100%;
  height: 400px;
}

.search-results {
  margin-top: 10px;
  list-style-type: none;
  padding-left: 0;
}

.search-results li {
  cursor: pointer;
  margin-top: 5px;
}
</style>
